﻿using System;
using System.Drawing;
using System.Windows.Forms;
using QuanLyThongTinCoSo.Biz;
using QuanLyThongTinCoSo.Common;
using QuanLyThongTinCoSo.Entity;


namespace QuanLyThongTinCoSo.Forms.Settings
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
        }

        private void FormLoad(object sender, EventArgs e)
        {
            textAccount.Focus();
        }

        private void Login(object sender, EventArgs e)
        {
            if(Validation())
            {
                var context = new Entities();
                var biz = new UserBiz(context);
                var currentUser = biz.Login(textAccount.Text, textPassword.Text);

                if (MdiParent != null && currentUser != null)
                {
                    var parrent = (MDI)MdiParent;
                    parrent.CurrentUser = currentUser;
                    parrent.UserStatus = string.Concat(Constants.Messages.Welcome, currentUser.FullName);

                    parrent.ShowMenu(true);
                    Utilities.ShowMdi(this);
                }

                if(currentUser == null)
                {
                    labelMessage.Text = Constants.Messages.CannotLogin;
                }
            }
        }

        private bool Validation()
        {
            bool hasError = true;
            bool isFocused = false;
            labelMessage.Text = string.Empty;
            errorProvider.Clear();

            if (string.IsNullOrEmpty(textAccount.Text))
            {
                errorProvider.SetError(textAccount, Constants.Messages.RequireMessage);
                hasError = false;

                textAccount.Focus();
                isFocused = true;
            }

            if (string.IsNullOrEmpty(textPassword.Text))
            {
                errorProvider.SetError(textPassword, Constants.Messages.RequireMessage);
                hasError = false;

                if (!isFocused)
                {
                    textPassword.Focus();
                }
            }

            return hasError;
        }

        protected void ChangeSize(object sender, EventArgs e)
        {
            int width = Size.Width / 2 - groupBox1.Size.Width / 2;
            int height = Size.Height / 2 - groupBox1.Size.Height / 2;
            groupBox1.Location = new Point(width, height);
        }
    }
}
